# -*- coding: utf-8 -*-

import json
import logging
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import UserError, ValidationError
from .api_base import APIBaseController

_logger = logging.getLogger(__name__)


class PermissionController(APIBaseController):
    """权限管理控制器"""



    @http.route('/api/system/menu/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def menu_list(self, **kwargs):
        """权限菜单列表"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:menu:list'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs or {}
            
            # 构建查询条件
            domain = []
            
            # 菜单名称查询
            if data.get('menuName'):
                domain.append(('name', 'ilike', data['menuName']))
            
            # 状态查询
            if 'status' in data:
                domain.append(('status', '=', data['status'] == '0'))
            
            # 查询权限菜单
            permissions = request.env['device.permission'].sudo().search(domain, order='sequence, name')
            
            # 构建树形结构
            def build_tree(parent_id=None):
                children = []
                for perm in permissions.filtered(lambda x: x.parent_id.id == (parent_id or False)):
                    perm_data = {
                        'menuId': perm.id,
                        'menuName': perm.name,
                        'parentId': perm.parent_id.id if perm.parent_id else 0,
                        'orderNum': perm.sequence,
                        'path': perm.menu_path,
                        'component': perm.component,
                        'query': '',
                        'isFrame': perm.is_frame,
                        'isCache': perm.is_cache,
                        'menuType': perm.permission_type,
                        'visible': perm.visible,
                        'status': perm.status,
                        'perms': perm.perms,
                        'icon': perm.icon,
                        'createTime': perm.create_time and perm.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                        'children': build_tree(perm.id)
                    }
                    children.append(perm_data)
                return children
            
            tree_data = build_tree()
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': tree_data
            }
            
        except Exception as e:
            _logger.error(f"查询菜单列表异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}

    @http.route('/api/system/menu', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def menu_add(self, **kwargs):
        """新增菜单"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:menu:add'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            
            # 验证必填字段
            if not data.get('menuName'):
                return {'code': 500, 'msg': '菜单名称不能为空', 'data': None}
            if not data.get('menuType'):
                return {'code': 500, 'msg': '菜单类型不能为空', 'data': None}
            
            # 创建权限菜单
            perm_vals = {
                'name': data['menuName'],
                'permission_type': data['menuType'],
                'sequence': data.get('orderNum', 10),
                'menu_path': data.get('path'),
                'component': data.get('component'),
                'icon': data.get('icon'),
                'perms': data.get('perms'),
                'visible': data.get('visible', True),
                'status': data.get('status', True),
                'is_frame': data.get('isFrame', False),
                'is_cache': data.get('isCache', False),
                'create_by': current_user.id
            }
            
            # 父菜单
            if data.get('parentId') and data['parentId'] != 0:
                perm_vals['parent_id'] = data['parentId']
            
            # 生成权限编码（如果未提供）
            if not data.get('perms') and data['menuType'] == 'F':
                # 按钮权限自动生成编码
                parent_perms = ''
                if data.get('parentId'):
                    parent = request.env['device.permission'].sudo().browse(data['parentId'])
                    if parent.exists():
                        parent_perms = parent.perms or ''
                perm_vals['perms'] = f"{parent_perms}:{data['menuName'].lower()}"
            
            # 自动生成编码
            if not perm_vals.get('code'):
                perm_vals['code'] = f"menu_{data['menuName'].lower()}_{perm_vals['permission_type']}"
            
            new_perm = request.env['device.permission'].sudo().create(perm_vals)
            
            return {'code': 200, 'msg': '新增成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"新增菜单异常: {str(e)}")
            return {'code': 500, 'msg': f'新增失败: {str(e)}', 'data': None}

    @http.route('/api/system/menu/<int:menu_id>', type='json', auth='none', methods=['PUT'], csrf=False, cors='*')
    def menu_edit(self, menu_id, **kwargs):
        """修改菜单"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:menu:edit'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            
            # 查找菜单
            permission = request.env['device.permission'].sudo().browse(menu_id)
            if not permission.exists():
                return {'code': 500, 'msg': '菜单不存在', 'data': None}
            
            # 更新菜单信息
            perm_vals = {
                'update_by': current_user.id
            }
            
            if data.get('menuName'):
                perm_vals['name'] = data['menuName']
            if data.get('orderNum') is not None:
                perm_vals['sequence'] = data['orderNum']
            if 'path' in data:
                perm_vals['menu_path'] = data['path']
            if 'component' in data:
                perm_vals['component'] = data['component']
            if 'icon' in data:
                perm_vals['icon'] = data['icon']
            if 'perms' in data:
                perm_vals['perms'] = data['perms']
            if 'visible' in data:
                perm_vals['visible'] = data['visible']
            if 'status' in data:
                perm_vals['status'] = data['status']
            if 'isFrame' in data:
                perm_vals['is_frame'] = data['isFrame']
            if 'isCache' in data:
                perm_vals['is_cache'] = data['isCache']
            
            # 父菜单
            if 'parentId' in data:
                if data['parentId'] and data['parentId'] != 0:
                    perm_vals['parent_id'] = data['parentId']
                else:
                    perm_vals['parent_id'] = False
            
            permission.sudo().write(perm_vals)
            
            return {'code': 200, 'msg': '修改成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"修改菜单异常: {str(e)}")
            return {'code': 500, 'msg': f'修改失败: {str(e)}', 'data': None}

    @http.route('/api/system/menu/<int:menu_id>', type='json', auth='none', methods=['DELETE'], csrf=False, cors='*')
    def menu_delete(self, menu_id, **kwargs):
        """删除菜单"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:menu:remove'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            # 查找菜单
            permission = request.env['device.permission'].sudo().browse(menu_id)
            if not permission.exists():
                return {'code': 500, 'msg': '菜单不存在', 'data': None}
            
            # 检查是否有子菜单
            if permission.child_ids:
                return {'code': 500, 'msg': '存在子菜单，不允许删除', 'data': None}
            
            # 检查是否有角色使用该权限
            role_count = request.env['device.user.role'].sudo().search_count([
                ('permission_ids', 'in', [menu_id])
            ])
            if role_count > 0:
                return {'code': 500, 'msg': '菜单已分配，不允许删除', 'data': None}
            
            # 删除菜单
            permission.sudo().unlink()
            
            return {'code': 200, 'msg': '删除成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"删除菜单异常: {str(e)}")
            return {'code': 500, 'msg': f'删除失败: {str(e)}', 'data': None}

    @http.route('/api/system/menu/treeselect', type='json', auth='none', methods=['GET', 'POST'], csrf=False, cors='*')
    def menu_tree_select(self, **kwargs):
        """获取菜单下拉树列表"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 查询所有菜单
            permissions = request.env['device.permission'].sudo().search([], order='sequence, name')
            
            # 构建树形结构
            def build_tree_select(parent_id=None):
                children = []
                for perm in permissions.filtered(lambda x: x.parent_id.id == (parent_id or False)):
                    tree_data = {
                        'id': perm.id,
                        'label': perm.name,
                        'children': build_tree_select(perm.id)
                    }
                    children.append(tree_data)
                return children
            
            tree_data = build_tree_select()
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': tree_data
            }
            
        except Exception as e:
            _logger.error(f"获取菜单树异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}

    @http.route('/api/system/menu/roleMenuTreeselect/<int:role_id>', type='json', auth='none', methods=['GET'], csrf=False, cors='*')
    def role_menu_tree_select(self, role_id, **kwargs):
        """加载对应角色菜单列表树"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 查询所有菜单
            permissions = request.env['device.permission'].sudo().search([], order='sequence, name')
            
            # 构建树形结构
            def build_tree_select(parent_id=None):
                children = []
                for perm in permissions.filtered(lambda x: x.parent_id.id == (parent_id or False)):
                    tree_data = {
                        'id': perm.id,
                        'label': perm.name,
                        'children': build_tree_select(perm.id)
                    }
                    children.append(tree_data)
                return children
            
            tree_data = build_tree_select()
            
            # 获取角色已选择的菜单ID
            role = request.env['device.user.role'].sudo().browse(role_id)
            checked_keys = role.permission_ids.ids if role.exists() else []
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'menus': tree_data,
                    'checkedKeys': checked_keys
                }
            }
            
        except Exception as e:
            _logger.error(f"获取角色菜单树异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}
